<?php
/**
 * Created by PhpStorm.
 * User: 86158
 * Date: 2021/6/28
 * Time: 15:50
 */

namespace App\Admin\Controllers\access;

use App\Admin\Controllers\access\actions\ExporterAccessGrossMargin;
use App\Common\statement\CommonStatement;
use App\Models\access\AccessVote;
use App\Models\access\AccessVoteLeader;
use App\Models\access\AccessVoteLog;
use App\Models\access\AccessVoteMember;
use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid\Tools;
use Illuminate\Http\Request;
use James\Admin\Actions;
use James\Admin\Grid;
use Maatwebsite\Excel\Facades\Excel;

class AccessLogController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '投票考核得分记录表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AccessVoteLog());
        $grid->model()->where('is_del',0);
        $grid->disableExport();
        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->equal('access_id','考核ID');
        });
//        $grid->tools(function (Tools $tools) {
//            $tools->append(new ExporterAccessGrossMargin());//导出
//        });
        $grid->disableExport();
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->actions(function (Actions $actions) {
            $actions->disableView();
            $actions->disableEdit();
            $actions->disableDelete();
        });
        $grid->column('access_id',__('考核ID'));
        $grid->column('access.title',__('Title'));
        $grid->column('leader.name',__('投票领导'));
        $grid->column('user.name',__('被投票人'));
        $grid->column('level',__('投票结果'))->display(function ($level){
            return CommonStatement::level_vote[$level];
        });
        $grid->column('score',__('投票分数'))->display(function (){
            switch ($this->level){
                case 1 :
                    $score = $this->access->score_level_best;
                    break;
                case 2 :
                    $score = $this->access->score_level_good;
                    break;
                case 3 :
                    $score = $this->access->score_level_general;
                    break;
                case 4 :
                    $score = $this->access->score_level_poor;
                    break;
            }
            return $score;
        });

        $grid->column('rate',__('得分占比'))->display(function (){

            switch ($this->leader_type){
                case 1 :
                    $rate = $this->access->main_leader_rate;
                    break;
                case 2 :
                    $rate = $this->access->direct_leader_rate;
                    break;
                case 3 :
                    $rate = $this->access->other_leader_rate;
                    break;
            }
            return $rate;
        });
        $grid->column('score_total',__('得分小计'))->display(function (){
            switch ($this->level){
                case 1 :
                    $score = $this->access->score_level_best;
                    break;
                case 2 :
                    $score = $this->access->score_level_good;
                    break;
                case 3 :
                    $score = $this->access->score_level_general;
                    break;
                case 4 :
                    $score = $this->access->score_level_poor;
                    break;
            }
            switch ($this->leader_type){
                case 1 :
                    $rate = $this->access->main_leader_rate;
                    break;
                case 2 :
                    $rate = $this->access->direct_leader_rate;
                    break;
                case 3 :
                    $rate = $this->access->other_leader_rate;
                    break;
            }
            return bcmul($score,$rate,2);
        });
        $grid->column('rank',__('排名'));
        $grid->column('remark',__('评价'));
        return $grid;
    }


    /**
     * 导出
     * @return mixed
     */
    public function exports(Request $request)
    {
        $access_id = $request->access_id;
        if(!$access_id){
            exit;
        }
        $access = AccessVote::where('id',$access_id)->where('status',2)->first();
        if(!$access){
            return admin_error('暂无法导出','暂无法导出');
        }
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(app_path().'/Admin/Extensions/Excel/access_vote_template.xls');
        $worksheet = $spreadsheet->getActiveSheet();

        $title = "广安市人力资源和社会保障局公务员（参公人员）平时考核民主测评表汇总表";
        $worksheet->setCellValueByColumnAndRow(1,1,$title);

        $logData = $this->exportData($access_id);

        $leaderRow = 4;
        $leaderStartColumn = 4;
        $leaderColumn = 4;
        $leaderEndColumn = 11;
        $leaderData = AccessVoteLeader::where('access_id','=',$access_id)->where('leader_type',2)->with('user')->get()->toArray();

        /********分管领导姓名********/
        foreach ($leaderData as $leaderKey => $leaderVal){
            if($leaderVal['leader_type'] == 2){
                $worksheet->setCellValueByColumnAndRow($leaderColumn,$leaderRow,$leaderVal['user']['name']);
                $leaderColumn += 1;
            }
        }
        /**********隐藏分管领导多余列********/
        for ($leaderColumn ; $leaderColumn < $leaderEndColumn+1;$leaderColumn++){
            $spreadsheet->getActiveSheet()->getColumnDimensionByColumn($leaderColumn)->setVisible(false);
        }

        $worksheet->setCellValueByColumnAndRow(3,3,'主要领导('.bcmul($access['main_leader_rate'],100,0).'%)');
        $worksheet->setCellValueByColumnAndRow(4,3,'分管领导对分管领域('.bcmul($access['direct_leader_rate'],100,0).'%)');
        $worksheet->setCellValueByColumnAndRow($leaderEndColumn,3,'其他领导('.bcmul($access['other_leader_rate'],100,0).'%)');
        $worksheet->setCellValueByColumnAndRow($leaderEndColumn+2,3,'主要领导('.bcmul($access['main_leader_rate'],100,0).'%)');
        $worksheet->setCellValueByColumnAndRow($leaderEndColumn+3,3,'分管领导('.bcmul($access['direct_leader_rate'],100,0).'%)');
        $worksheet->setCellValueByColumnAndRow($leaderEndColumn+4,3,'其他领导('.bcmul($access['other_leader_rate'],100,0).'%)');

        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $startRow = 5;
        $count = count($logData);
        $worksheet->getStyleByColumnAndRow(1,$startRow,30,$startRow+$count)->applyFromArray($styleArray);
        $worksheet->getStyleByColumnAndRow(2,$startRow,30,$startRow+$count)->applyFromArray($styleArray);
        foreach ($logData as $key => $val){
            $worksheet->setCellValueByColumnAndRow(1,$startRow+$key,$val['order']);
            $worksheet->setCellValueByColumnAndRow(2,$startRow+$key,$val['user_name']);
            $worksheet->setCellValueByColumnAndRow(3,$startRow+$key,$val['main_leader_level_score']);

            /**********分管领导得分*********/
            foreach ($leaderData as $leaderKey => $leaderVal){
                if($leaderVal['leader_id'] == $val['direct_leader_level_score']['leader_id']){
                    $worksheet->setCellValueByColumnAndRow($leaderStartColumn+$leaderKey,$startRow+$key,$val['direct_leader_level_score']['level_score']);
                }
            }

            /**********其余领导*********/
            $leaderMap = [
                'access_id' => $access_id,
                'user_id' => $val['user_id'],
                'leader_type' => 3,
            ];
            $otherSum = 0;
            foreach ($val['other_leader_level_score'] as $other){
                $otherSum += $other['level_score'];
            }
            $otherLeaderScore = bcdiv($otherSum,count($val['other_leader_level_score']),0);
            $worksheet->setCellValueByColumnAndRow($leaderColumn,$startRow+$key,$otherLeaderScore);
            $leaderMap['leader_type'] = 1;
            $mainLeaderScore = AccessVoteLog::where($leaderMap)->avg('score');
            $worksheet->setCellValueByColumnAndRow($leaderColumn+1,$startRow+$key,$mainLeaderScore);
            $leaderMap['leader_type'] = 2;
            $directLeaderScore = AccessVoteLog::where($leaderMap)->avg('score');
            $worksheet->setCellValueByColumnAndRow($leaderColumn+2,$startRow+$key,$directLeaderScore);
            $leaderMap['leader_type'] = 3;
            $otherLeaderScore = AccessVoteLog::where($leaderMap)->avg('score');
            $worksheet->setCellValueByColumnAndRow($leaderColumn+3,$startRow+$key,$otherLeaderScore);
            $worksheet->setCellValueByColumnAndRow($leaderColumn+4,$startRow+$key,bcadd($mainLeaderScore,bcadd($directLeaderScore,$otherLeaderScore,2),2));
//            $worksheet->setCellValueByColumnAndRow($leaderColumn+5,$startRow+$key,$val['order']);
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $d = $writer->save('access_vote.xls');
        $response = response()->download(realpath(base_path('public')).'/access_vote.xls',$title.'.xls');
        ob_end_clean();
        return $response;
    }

    public function exportData($access_id)
    {
        $voted_user = AccessVoteMember::where('access_id','=',$access_id)
            ->with('user')->with('access.leader')
            ->with('access.leader.user')
            ->get()->toArray();
        $arr = [];
        foreach ($voted_user as $key => &$item){
            $item['order'] = $key + 1;
            $item['access_log'] = AccessVoteLog::where('access_id',$access_id)->get()->toArray();
                foreach ($item['access_log'] as $val){
                    if($val['user_id'] == $item['user_id']){
                        $level_score = $this->getLevelScore($val['level'],$item['access']);
                        if($val['leader_type'] == 1){
                            $item['main_leader_level_score'][] = [
                                'leader_id' => $val['vote_user_id'],
                                'level_score' => $level_score
                            ];
                        }
                        if($val['leader_type'] == 2){
                            $item['direct_leader_level_score'][] = [
                                'leader_id' => $val['vote_user_id'],
                                'level_score' => $level_score
                            ];
                        }
                        if($val['leader_type'] == 3){
                            $item['other_leader_level_score'][] = [
                                'leader_id' => $val['vote_user_id'],
                                'level_score' => $level_score
                            ];
                        }
                    }
            }
        }
        foreach ($voted_user as $value){
            $detail['order'] = $value['order'];
            $detail['user_id'] = $value['user_id'];
            $detail['user_name'] = $value['user']['name'];
            $detail['score'] = $value['score'];
            $detail['main_leader_level_score'] = $value['main_leader_level_score'][0]['level_score'];
            $detail['direct_leader_level_score'] = $value['direct_leader_level_score'][0];
            $detail['other_leader_level_score'] = $value['other_leader_level_score'];
//            foreach ($value['direct_leader_level_score'] as $directKey => $directVal){
//                $detail['direct_leader_level_score'.$directKey] = $directVal['level_score'];
//            }
//            foreach ($value['other_leader_level_score'] as $otherKey => $otherVal){
//                $detail['other_leader_level_score'.$otherKey] = $otherVal['level_score'];
//            }
            $arr[] = $detail;
        }
        return collect($arr);
    }

    public function getLevelScore($level,$access)
    {
        switch ($level){
            case 1 :
                $score = $access['score_level_best'];
                break;
            case 2 :
                $score = $access['score_level_good'];
                break;
            case 3 :
                $score = $access['score_level_general'];
                break;
            case 4 :
                $score = $access['score_level_poor'];
                break;
        }
        return $score;
    }



}